
/****** Object:  StoredProcedure [dbo].[web_ins_upd_klij]    Script Date: 10/19/2013 09:20:36 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

IF EXISTS (SELECT * FROM sys.objects WHERE type = 'P' AND name = 'web_ins_upd_klij')
DROP PROCEDURE web_ins_upd_klij
GO

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[web_ins_upd_klij]
	@N08_c_kodas_ks char(12),
	@N08_c_suma_wk_per char(10),
	@n08_c_kreditas_dienos char(3),
	@N08_kodas_ls_5 char(3),
	@n08_c_invoice varchar(200)
AS
BEGIN
	SET NOCOUNT ON;
	If @N08_kodas_ls_5='K01'
	begin
		If exists(SELECT * FROM n08_klij_c where N08_c_kodas_ks = @N08_c_kodas_ks)
			update n08_klij_c set N08_c_suma_wk_per = CASE WHEN ISNUMERIC(@N08_c_suma_wk_per)=1 THEN abs(CAST(@N08_c_suma_wk_per as numeric(8,0))) ELSE null END,
			n08_c_invoice = @n08_c_invoice where N08_c_kodas_ks = @N08_c_kodas_ks;
		else
			insert INto n08_klij_c ([N08_c_kodas_ks]
           ,[N08_c_suma_wk_per]
           ,[n08_c_kreditas_dienos]
		   ,[n08_c_invoice]) values (@N08_c_kodas_ks,
		   CASE WHEN ISNUMERIC(@N08_c_suma_wk_per)=1 THEN abs(CAST(@N08_c_suma_wk_per as numeric(8,0))) ELSE null END,
		   null,
		   @n08_c_invoice);
	end
	
	if @N08_kodas_ls_5='K02'
	begin
		If exists(SELECT * FROM n08_klij_c where N08_c_kodas_ks = @N08_c_kodas_ks)
			update n08_klij_c set N08_c_suma_wk_per = CASE WHEN ISNUMERIC(@N08_c_suma_wk_per)=1 THEN abs(CAST(@N08_c_suma_wk_per as numeric(8,0))) ELSE null END,
			n08_c_kreditas_dienos = CASE WHEN ISNUMERIC(@n08_c_kreditas_dienos)=1 THEN CAST(@n08_c_kreditas_dienos as numeric(3,0)) ELSE null END,
			n08_c_invoice = @n08_c_invoice
			 where N08_c_kodas_ks = @N08_c_kodas_ks;
		else
			insert INto n08_klij_c ([N08_c_kodas_ks]
           ,[N08_c_suma_wk_per]
           ,[n08_c_kreditas_dienos]
		   ,[n08_c_invoice]) values (@N08_c_kodas_ks,abs(CAST(@N08_c_suma_wk_per as numeric(8,0))), CASE WHEN ISNUMERIC(@n08_c_kreditas_dienos)=1 THEN CAST(@n08_c_kreditas_dienos as numeric(3,0)) ELSE null END,
		   @n08_c_invoice);
	
	end
    
	if @N08_kodas_ls_5 not in ('K02','K01') or @N08_kodas_ls_5 is null
	begin
		If exists(SELECT * FROM n08_klij_c where N08_c_kodas_ks = @N08_c_kodas_ks)
			update n08_klij_c set 
			n08_c_invoice = @n08_c_invoice where N08_c_kodas_ks = @N08_c_kodas_ks;		
		else
			insert INto n08_klij_c ([N08_c_kodas_ks]           
           ,[n08_c_kreditas_dienos]
		   ,[n08_c_invoice]) values (@N08_c_kodas_ks,
		   null,
		   @n08_c_invoice);		
	end
	
END

GO



